package com.ds.infra.rpc.example.provider.dao;

import com.ds.infra.rpc.example.api.dto.ProductDTO;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

@Repository
public class ProductRepository {
    private final Map<Long, ProductDTO> productStore = new ConcurrentHashMap<>();

    public ProductRepository() {
        // 初始化测试数据
        ProductDTO p1 = new ProductDTO();
        p1.setId(1L);
        p1.setName("iPhone 13");
        p1.setPrice(new BigDecimal("5999.00"));
        p1.setStock(100);

        ProductDTO p2 = new ProductDTO();
        p2.setId(2L);
        p2.setName("MacBook Pro");
        p2.setPrice(new BigDecimal("12999.00"));
        p2.setStock(50);

        productStore.put(1L, p1);
        productStore.put(2L, p2);
    }

    public Optional<ProductDTO> findById(Long id) {
        return Optional.ofNullable(productStore.get(id));
    }

    public List<ProductDTO> findAll() {
        return new ArrayList<>(productStore.values());
    }

    public List<ProductDTO> findAllById(List<Long> ids) {
        return ids.stream()
                .map(productStore::get)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
    }

    public void save(ProductDTO product) {
        productStore.put(product.getId(), product);
    }
}
